import plugin from '../../lib/plugins/plugin.js'
import { segment } from "oicq"; 

const api_key = '0a0fba6493d353569f5225f588b67ddedf266d1a';
//   console.log(api_key) 
//api_key只要填进上面引号里,自行去https://saucenao.com/user.php注册账号然后在https://saucenao.com/user.php?page=search-api找到属于你的api

//v2.2由一葉修改，后续修改者请标号注释
//v2.3添加p外danbooro源的识别
//v2.4添加kemono中fanbox识别,根据行歌的思路初步修复.data字段报错问题
//如果搜图发现没有出处或者是undefined，可以把所搜图片发与一葉添加识别或者自行添加识别


export class soutu extends plugin {
  constructor () {
    super({
      name: '搜图',
      dsc: '搜图【带上图】',
      event: 'message',
      priority: 5000,
      rule: [
        {
          reg: '^#*搜图$',
          fnc: 'soutu'
        },
        {
            reg: '^#*找图$',
            fnc: 'zhaotu'
          },
      ]
    })
  }

  async zhaotu (e) {
    e.reply('时间有点长，请耐心等待')
    let img = e.img[0];
    let response1 = await fetch('https://ascii2d.net/search/uri?uri=' + img, {
        method: 'POST',
        headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
        }
    });
    let cookies = response1.headers.get('set-cookie');
    let sessionId = cookies.match(/_session_id=([^;]+)/);

    let imageIdMatch = img.match(/(?<=-)\w+(?=\/)/);
    let imageId = imageIdMatch[0].toLowerCase();

    let response2 = await fetch(`https://ascii2d.net/search/bovw/${imageId}`, {
        headers: {
        'Cookie': sessionId,
        'Content-Type': 'application/x-www-form-urlencoded'
        }
    });
    let html = await response2.text();

    // 图片链接
    let thumbnailRegex = /\/thumbnail\/(\w+\/){1,}\w+\.\w+/g;
    let thumbnailUrls = html.match(thumbnailRegex);
    // 结果链接
    let regex = /<a target="_blank" rel="noopener" href="(.*?)">(.*?)<\/a>/g;
    let Urls = html.match(regex);
    let data_msg = [];
    
    let j = 1;
    for (let i in Urls){
        if(i > 0 && i % 2 == 1){
            let jg = Urls[i].match(/<a target="_blank" rel="noopener" href="(.*?)">(.*?)<\/a>/);
            if(!jg)break;
            let c = Urls[i-1].match(/<a target="_blank" rel="noopener" href="(.*?)">(.*?)<\/a>/);
            console.log('jg==' + jg)
            console.log('c==' + c)
            console.log('img==' + thumbnailUrls[j])
            data_msg.push({
                message: [
                    `链接：${c[1]}\n标题：${c[2]}\n`,
                    `作者：${jg[2]}\n主页：${jg[1]}`,
                    segment.image('https://ascii2d.net' + thumbnailUrls[j])
                ],
                nickname: e.nickname,
                user_id: e.user_id
            })
            if(j = 3)break;
            j = +j+1;
        }
    }
    //创建合并转发消息
    let ForwardMsg;
        if (this.e.isGroup) {
            ForwardMsg = await e.group.makeForwardMsg(data_msg);
        } else {
            ForwardMsg = await e.friend.makeForwardMsg(data_msg);
        }
        e.reply(ForwardMsg)//发送消息
        return true;

  }
 
  async soutu (e) {
    if (e.source) {
        let reply = (await e.group.getChatHistory(e.source.seq, 1)).pop()?.message;
        if (reply) {
            for (let val of reply) {
                if (val.type == "image") {
                    e.img = [val.url];
                    break;
                }
            }
        }
    }
    
    try {
       
        if (!e.img) {
            e.reply("请和图一起发送")
            return true;
        }

        //api_key验证
        if (api_key == '') {
            let msg = [
                "请自行去saucenao.com注册账号并获取api_key！"
            ]
            e.reply(msg);
            return false;
        } 
        e.reply("需要花点时间哦")
        let imgURL = e.img[0];
        let url;
        if (imgURL.length > 0) {
            url = "https://saucenao.com/search.php";
        }

        let response = await fetch(`https://saucenao.com/search.php?output_type=2&api_key=${api_key}&db=999&numres=3&url=${encodeURI(imgURL)}`)
        let res = await response.json();
        // console.log(response);

        let long_remaining = res.header.long_remaining;//一天内剩余搜图次数

        let penable = false;
        let jp = false;
        let danb = false;
        let pother = false;
        let da = false;
        let k = 0;

        //优先p站源，其次danbooru，再其次携带日文名，最后是其他
        if (res) {
            let i = 0;
            for (i; i < 3; i++) {
                if (res.results[i].data.pixiv_id) {console.log('penable'); penable = true; k = i; break; }
                else if (res.results[i].data.ext_urls) {
                    for (let j = 0; j < res.results[i].data.ext_urls.length; j++) {
                        if (res.results[i].data.ext_urls[j].indexOf('pixiv') != -1) {
                            console.log('pother'); pother = true; k = i; break;
                        }
                        if (pother) { break; }
                    }
                }
                else if (res.results[i].data.ext_urls) {
                    for (let j = 0; j < res.results[i].data.ext_urls.length; j++) {
                        if (res.results[i].data.ext_urls[j].indexOf('danbooru') != -1) {
                            console.log('danb'); danb = true; k = i; break;
                        }
                        if (danb) { break; }
                    }
                }
                else if (res.results[i].data.jp_name) {console.log('jp'); jp = true; k = i; break; }
                else if (res.results[i].data.da_id) {console.log('da'); da = true; k = i; break; }
                else {console.log('no'); penable = false; k = 0; }
            }
        }

        //过滤相似度<=70%的图片，并返回首张图片
        if (res.results[k].header.similarity <= 70) { k = 0; }

        let msg;

        // console.log(`penable:${penable}`)

        if (penable) {
            //p中danbooru源
            let pdanb = false;
            if (res.results[k].data.ext_urls) {
                for (let j = 0; j < res.results[k].data.ext_urls.length; j++) {
                    if (res.results[k].data.ext_urls[j].indexOf('danbooru') != -1)
                        pdanb = true; break;
                }
            }
            if (pdanb) {
                msg = [segment.at(e.user_id), '\n',
                    "相似度：" + res.results[k].header.similarity + "%\n",
                    "danbooru_id：" + (res.results[k].data.danbooru_id ? res.results[k].data.danbooru_id : ''), '\n',
                    "gelbooru_id：" + (res.results[k].data.gelbooru_id ? res.results[k].data.gelbooru_id : ''), '\n',
                    "creator：" + (res.results[k].data.creator ? res.results[k].data.creator : ''), '\n',
                    "material：" + (res.results[k].data.material ? res.results[k].data.material : ''), '\n',
                    "characters：" + (res.results[k].data.characters ? res.results[k].data.characters : ''), '\n',
                    "来源：" + (res.results[k].data.source ? res.results[k].data.source : ''), '\n',
                    "链接：" + res.results[k].data.ext_urls[0], '\n',
                    segment.image(res.results[k].header.thumbnail), '\n',
                    "一天内还可搜索" + long_remaining + "次"
                ]
            }
            //p站源
            else {
                let url = 'https://px3.rainchan.win/json/'+res.results[k].data.pixiv_id;
                let response = await fetch(url).catch((err) => logger.error(err)); //调用接口获取数据
                let obj = await response.json();
                // 屏蔽r18图片
                let img;
                if(obj && obj.error === false){
                    img = segment.image(obj.body[0].urls.original.replace(/pixiv\.net/g, 'pixiv.re'));
                    
                }else{
                    img = segment.image(`https://pixiv.re/${res.results[k].data.pixiv_id}.jpg`);
                }
                msg = [segment.at(e.user_id), '\n',
                    "相似度：" + res.results[k].header.similarity + "%\n",
                    "标题：" + (res.results[k].data.title ? res.results[k].data.title : ''), '\n',
                    "P站ID：" + (res.results[k].data.pixiv_id ? res.results[k].data.pixiv_id : ''), '\n',
                    "画师：" + (res.results[k].data.member_name ? res.results[k].data.member_name : ''), '\n',
                    "来源：" + res.results[k].data.ext_urls[0], '\n',
                    `直链：https://pixiv.re/${res.results[k].data.pixiv_id}.jpg\n`,
                    img, '\n',
                    "一天内还可搜索" + long_remaining + "次"
                ];
                // console.log(msg)
            }
        }
        else if (danb) {
            msg = [segment.at(e.user_id), '\n',
            "相似度：" + res.results[k].header.similarity + "%\n",
            "danbooru_id：" + (res.results[k].data.danbooru_id ? res.results[k].data.danbooru_id : ''), '\n',
            "gelbooru_id：" + (res.results[k].data.gelbooru_id ? res.results[k].data.gelbooru_id : ''), '\n',
            "creator：" + (res.results[k].data.creator ? res.results[k].data.creator : ''), '\n',
            "material：" + (res.results[k].data.material ? res.results[k].data.material : ''), '\n',
            "characters：" + (res.results[k].data.characters ? res.results[k].data.characters : ''), '\n',
            "来源：" + (res.results[k].data.source ? res.results[k].data.source : ''), '\n',
            "链接：" + res.results[k].data.ext_urls[0], '\n',
            segment.image(res.results[k].header.thumbnail), '\n',
            "一天内还可搜索" + long_remaining + "次"
            ]
        }

        else if (pother) {
            msg = msg = [
                segment.at(e.user_id), '\n',
                "相似度：" + res.results[k].header.similarity + "%\n",
                "标题：" + (res.results[k].data.title ? res.results[k].data.title : ''), '\n',
                "service：" + (res.results[k].data.service ? res.results[k].data.service : ''), '\n',
                "画师ID：" + (res.results[k].data.user_id ? res.results[k].data.user_id : ''), '\n',
                "来源：" + res.results[k].data.ext_urls[0], '\n',
                segment.image(res.results[k].header.thumbnail), '\n',
                "一天内还可搜索" + long_remaining + "次"
            ];
        }

        else if (jp) {
            msg = [
                segment.at(e.user_id), '\n',
                "相似度：" + res.results[k].header.similarity + "%\n",
                "画师：" + (res.results[k].data.creator ? res.results[k].data.creator : ''), '\n',
                "来源：" + (res.results[k].data.source ? res.results[k].data.source : ''), '\n',
                "日文名：" + (res.results[k].data.jp_name ? res.results[k].data.jp_name : ''), '\n',
                segment.image(res.results[k].header.thumbnail), '\n',
                "一天内还可搜索" + long_remaining + "次"
            ]
        }
        else if (da) {
            msg = [
                segment.at(e.user_id), '\n',
                "相似度：" + res.results[k].header.similarity + "%\n",
                "画师：" + (res.results[k].data.author_name ? res.results[k].data.author_name : ''), '\n',
                "来源：" + (res.results[k].data.ext_urls[0] ? res.results[k].data.ext_urls[0] : ''), '\n',
                "标题：" + (res.results[k].data.title ? res.results[k].data.title : ''), '\n',
                segment.image(res.results[k].header.thumbnail), '\n',
                "一天内还可搜索" + long_remaining + "次"
            ]
        }
        else {
            msg = [
                segment.at(e.user_id), '\n',
                "相似度：" + res.results[k].header.similarity + "%\n",
                "画师：" + res.results[k].data.creator || res.results[k].data.author || res.results[k].data.author_name, '\n',
                "来源：" + res.results[k].data.source || res.results[k].data.author_url, '\n',
                segment.image(res.results[k].header.thumbnail), '\n',
                "一天内还可搜索" + long_remaining + "次"
            ]
        }
        e.reply(msg);
    } catch (err) {
        console.error(err);
        let msg = [
            "请先尝试重启Yunzai再搜图，\n",
            "若仍报错则请将控制台报错信息和所搜图片发给插件修改者反馈bug"
        ]
        e.reply(msg);
    }
   
    return true;//返回true 阻挡消息不再往下
    
    }

  }

